NugMiniPet = CreateFrame("Frame","NugMiniPet")

NugMiniPet:SetScript("OnEvent", function(self, event, ...)
	self[event](self, event, ...)
end)

local print = function(...)
    DEFAULT_CHAT_FRAME:AddMessage(...)
end

NugMiniPet:RegisterEvent("ADDON_LOADED")

local id_now
local lastCall
local DB_VERSION = 2

BINDING_HEADER_NUGMINIPET = "NugMiniPet"

function NugMiniPet.ADDON_LOADED(self,event,arg1)
    if arg1 == "NugMiniPet" or arg1 == "CWDGBLZPlus" or arg1 == "CWDGPowerUI" then
        NugMiniPetDB = NugMiniPetDB or {}
        NugMiniPetDB.pets = NugMiniPetDB.pets or {}
        NugMiniPetDB.timer = NugMiniPetDB.timer or 0
        NugMiniPetDB.enable = (NugMiniPetDB.enable == nil) and true or NugMiniPetDB.enable

        for i=1,GetNumCompanions("CRITTER") do
            local _, creatureName, _, _, isSummoned = GetCompanionInfo("CRITTER", i)
            if isSummoned then id_now = i; break end
        end
        lastCall = GetTime()

        NugMiniPet:RegisterEvent("COMPANION_LEARNED")

--~     PURGING OLD DB OF PETS
        if not NugMiniPetDB.DB_VERSION or NugMiniPetDB.DB_VERSION ~= DB_VERSION then
            NugMiniPetDB.pets = {}
            NugMiniPetDB.DB_VERSION = DB_VERSION
        end


        hooksecurefunc("MoveForwardStart",NugMiniPet.Summon)
        hooksecurefunc("ToggleAutoRun",NugMiniPet.Summon)

        hooksecurefunc("CallCompanion",function(compType, id)
            if compType == "CRITTER" then
                id_now = id
                lastCall = GetTime()
            end
        end)
        hooksecurefunc("CompanionButton_OnModifiedClick",function(self,button)
            if ( PetPaperDollFrameCompanionFrame.mode ~= "CRITTER" ) then return end
            if IsControlKeyDown() then
                local offset = (PetPaperDollFrameCompanionFrame.pageCritter or 0) * NUM_COMPANIONS_PER_PAGE;
                local index = self:GetID() + offset
                local creatureID, creatureName, _, _, _ = GetCompanionInfo("CRITTER", index)
                if not NugMiniPetDB.pets[creatureID] then
                    NugMiniPetDB.pets[creatureID] = { creatureName = creatureName, index = index }
                    self.nmpBorder:Show()
                else
                    NugMiniPetDB.pets[creatureID] = nil
                    self.nmpBorder:Hide()
                end
            end
        end)
        hooksecurefunc("PetPaperDollFrame_UpdateCompanions",NugMiniPet.UpdateBorders)

        NugMiniPet.Auto_Button = self:CreateCheckBox()
        NugMiniPet.Timer_EditBox = self:CreateTimerEditBox()
        hooksecurefunc("PetPaperDollFrame_SetTab",function(id)
            if id == 2 then
                NugMiniPet.Auto_Button:Show()
                NugMiniPet.Timer_EditBox:Show()
            else
                NugMiniPet.Auto_Button:Hide()
                NugMiniPet.Timer_EditBox:ClearFocus()
                NugMiniPet.Timer_EditBox:Hide()
            end
        end)

    end
end

--~ function npdebug()
--~     for i,pet in pairs(NugMiniPetDB.pets) do
--~         print("ID:"..pet.index)
--~         print("name:"..pet.creatureName)
--~         print("crID:"..i)
--~         print("----------")
--~     end
--~ end

function NugMiniPet.Summon()
            if not NugMiniPetDB.enable then return end
            local creatureID,creatureName, isSummoned, timerExpired
            if id_now then
                creatureID, creatureName, _, _, isSummoned = GetCompanionInfo("CRITTER", id_now)
            end
            if NugMiniPetDB.timer ~= 0 then
                if lastCall + NugMiniPetDB.timer * 60 < GetTime() and select(2,NugMiniPet:Shuffle()) > 1 then timerExpired = true end
            end
            if not isSummoned or timerExpired then
                local id = NugMiniPet:Shuffle()
                while id_now ~= nil and id == id_now and select(2,NugMiniPet:Shuffle()) > 1 do
                    id = NugMiniPet:Shuffle()
                end
                if id and (lastCall+1.5 < GetTime()) and not UnitAffectingCombat("player") and not IsMounted() and not IsFlying() and not UnitHasVehicleUI("player") and not IsStealthed() and not UnitIsGhost("player") then
                    lastCall = GetTime() -- isSummoned seems like not updated instantly so this is a cooldown for next summon
                    CallCompanion("CRITTER",id)
                end
            end
end

function NugMiniPet.SimpleSummon()
    local id = NugMiniPet:Shuffle()
    while id_now ~= nil and id == id_now and select(2,NugMiniPet:Shuffle()) > 1 do
        id = NugMiniPet:Shuffle()
    end
    lastCall = GetTime()
    CallCompanion("CRITTER",id)
end

function NugMiniPet.UpdateBorders(self)
            if PetPaperDollFrameCompanionFrame.mode ~= "CRITTER" then
                for i=1,NUM_COMPANIONS_PER_PAGE do
                    local btn = getglobal("CompanionButton"..i)
                    if btn.nmpBorder then
                        btn.nmpBorder:Hide()
                    end
                end
                return
            end
            local offset = (PetPaperDollFrameCompanionFrame.pageCritter or 0) * NUM_COMPANIONS_PER_PAGE;
            for i=1,NUM_COMPANIONS_PER_PAGE do
                local btn = getglobal("CompanionButton"..i)
                local index = i + offset
                if btn.creatureID then
                    if not btn.nmpBorder then NugMiniPet:CreateBorder(btn) end
                    if NugMiniPetDB.pets[btn.creatureID] then
                        btn.nmpBorder:Show()
                    else
                        btn.nmpBorder:Hide()
                    end
                else
                    if btn.nmpBorder then btn.nmpBorder:Hide() end
                end
            end
end

function NugMiniPet.COMPANION_LEARNED(self)
	-- Rebuild all index fields in the DB after learning a new companion
    local creatureID
	for i=1,GetNumCompanions("CRITTER") do
		creatureID = GetCompanionInfo("CRITTER", i)
		if not creatureID then break end
		if NugMiniPetDB.pets[creatureID] then
			NugMiniPetDB.pets[creatureID].index = i
		end
	end
	self:UpdateBorders()
end

function NugMiniPet.CreateBorder(self,button)
    local b = button:CreateTexture(nil,"OVERLAY")
    b:SetTexture("Interface\\Buttons\\UI-Button-Outline")
    b:SetBlendMode("ADD")
    b:SetWidth(66)
    b:SetHeight(66)
    b:SetPoint("CENTER",button)
    b:SetVertexColor(0,0.8,0)
    b:Hide()
    button.nmpBorder = b
end

function NugMiniPet.CreateCheckBox(self)
    local f = CreateFrame("CheckButton",nil,CompanionNextPageButton,"UICheckButtonTemplate")
    f:SetWidth(25)
    f:SetHeight(25)
    f:SetPoint("LEFT",CompanionNextPageButton,"RIGHT",2,0)
    f:SetChecked(NugMiniPetDB.enable)
    f:SetScript("OnClick",function(self,button)
        NugMiniPetDB.enable = not NugMiniPetDB.enable
--~         print("NugMiniPet "..(NugMiniPetDB.enable and "enabled" or "disabled"),0.7,0.7,1)
    end)
    f:SetScript("OnEnter",function(self)
        GameTooltip:SetOwner(self, "ANCHOR_BOTTOMRIGHT")
        GameTooltip:SetText("NugMiniPet\nEnable/Disable Autosummon\n\nCtrlClick : Select pet", nil, nil, nil, nil, 1);
        GameTooltip:Show();
    end)
    f:SetScript("OnLeave",function(self)
        GameTooltip:Hide();
    end)

    local label  =  f:CreateFontString(nil, "OVERLAY")
    label:SetFontObject("GameFontNormal")
    label:SetPoint("LEFT",f,"RIGHT",0,0)
    label:SetText("Auto")

    return f
end

function NugMiniPet.CreateTimerEditBox()
    local f = CreateFrame("EditBox",nil,CompanionPrevPageButton,"InputBoxTemplate")
    f:SetWidth(30)
    f:SetHeight(15)
    f:SetAutoFocus(false)
    f:SetMaxLetters(3)
    f:SetText(NugMiniPetDB.timer)
    f:SetPoint("RIGHT",CompanionPrevPageButton,"LEFT",-15,0)
    f:SetScript("OnEnterPressed", function(self)
        if tonumber(self:GetText()) then
            NugMiniPetDB.timer = tonumber(self:GetText())
        end
        self:ClearFocus()
    end)
    f:SetScript("OnEscapePressed", function(self)
        self:SetText(NugMiniPetDB.timer)
        self:ClearFocus()
    end)

    f:SetScript("OnEnter",function(self)
        GameTooltip:SetOwner(self, "ANCHOR_BOTTOMRIGHT")
        GameTooltip:SetText("Summon new pet every X minutes\n0 = Disabled", nil, nil, nil, nil, 1);
        GameTooltip:Show();
    end)
    f:SetScript("OnLeave",function(self)
        GameTooltip:Hide();
    end)

    local label  =  f:CreateFontString(nil, "OVERLAY")
    label:SetFontObject("GameFontNormal")
    label:SetPoint("LEFT",f,"RIGHT",0,0)
    label:SetText("m")

    return f
end

function NugMiniPet.Shuffle(self)
    local maxn = 0
    for i in pairs(NugMiniPetDB.pets) do
        maxn = maxn + 1
    end
    if maxn == 0 then return nil, maxn end
    local random = math.random(maxn)
    local n = 1
    for creatureID, other in pairs(NugMiniPetDB.pets) do
        if n == random then return other.index, maxn end
        n = n + 1
    end
    return nil, maxn
end
